package com.hry.store.controller;

import com.github.pagehelper.PageInfo;
import com.hry.store.common.Const;
import com.hry.store.common.ServerResponse;
import com.hry.store.pojo.*;
import com.hry.store.service.*;
import com.hry.store.util.BigDecimalUtil;
import com.hry.store.vo.ShippingVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

@Controller
public class OrderController {

    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShippingService shippingService;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private ShippingVoService shippingVoService;

    BigDecimal totalPrice = new BigDecimal("0.0");

    /**
     * 确认订单
     */
    @RequestMapping("order/confirmOrder")
    public String confirmOrder(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (null == user) {
            return "login";
        }
        // 查询地址
        List<Shipping> shippings = shippingService.findShippingByEmail(user.getUserEmail());
        if (!CollectionUtils.isEmpty(shippings)) {
            modelMap.put("shippings", shippings);
        }
        // 查询选中的商品
        List<CartItem> cartItems = cartService.findByEmail(user.getUserEmail());

        if (!CollectionUtils.isEmpty(cartItems)) {
            modelMap.put("cartItems", cartItems);
        }
        for (CartItem cartItem : cartItems) {
            totalPrice = BigDecimalUtil.add(totalPrice.doubleValue(), cartItem.getProductTotalPrice().doubleValue());
        }
        modelMap.put("totalPrice", totalPrice);
        totalPrice = new BigDecimal("0.0");
        // 查询所有省份
        List<Province> provinceList = provinceService.getAll();
        if (!CollectionUtils.isEmpty(provinceList)) {
            modelMap.put("provinceList", provinceList);
        }

        return "confirm_order";
    }

    /**
     * 生成订单 -- 去数据库查询checked = 1 的商品  --仓库数量减少
     */
    @RequestMapping("order/createOrder")
    @ResponseBody
    public ServerResponse createOrder(HttpServletRequest request, ModelMap modelMap, @RequestParam("shippingId") Integer shippingId) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(Const.ERROR_CODE, "请先登录");
        }
        // 去购物车表查询checked= 1 的订单
        List<CartItem> cartItems = cartService.findByEmail(user.getUserEmail());
        Long orderNo = generateOrderNum();
        Order order = new Order();
        // 写入订单表中
        for (CartItem cartItem : cartItems) {
            order.setOrderNum(orderNo);
            order.setUserEmail(user.getUserEmail());
            order.setColorName(cartItem.getColorName());
            order.setProductId(cartItem.getProductId());
            order.setProductName(cartItem.getProductName());
            order.setProductImg(cartItem.getProductImg());
            order.setVersionId(cartItem.getVersionId());
            // 未支付
            order.setPaymentStatus(0);
            // 订单状态 0--下单成功 未支付
            order.setOrderStatus(0);
            order.setPayment(totalPrice);
            order.setShippingId(shippingId);
            order.setProductPrice(cartItem.getProductPrice());
            order.setProductQuantity(cartItem.getQuantity());
            order.setProductTotalPrice(cartItem.getProductTotalPrice());
            orderService.addToOrder(order);
            // 修改商品数量
            //goto

            // 从购物车中删除
//            cartService.deleteFromMysql(cartItem.getProductId(),cartItem.getProductName(),cartItem.getProductPrice(),cartItem.getVersionId(),cartItem.getColorName(),user.getUserEmail());
        }

        // 从数据库查，显示到付款界面  --收货地址 --支付总金额  --支付平台 --支付状态
        return ServerResponse.createBySuccess("下单成功", orderNo);

    }

    // 生成订单号
    private long generateOrderNum() {
        long currentTime = System.currentTimeMillis();
        return currentTime + new Random().nextInt(100);
    }

    /**
     * 用户订单查询
     */
    @RequestMapping("order/getByUserEmail")
    public String getByUserEmail(HttpServletRequest request, ModelMap modelMap, @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
//        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
//        if (user == null) {
//            return "login";
//        }
        PageInfo<Order> orders = orderService.getByEmail("2507511047@qq.com", pageSize, pageNum);
        modelMap.put("orders", orders);
        return "my_order";
    }

    /**
     * 跳转到订单明细
     */
    @RequestMapping("order/page/orderDetail")
    public String orderDetail(HttpServletRequest request, @RequestParam("orderNo") Long orderNo, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return "login";
        }
        List<Order> orderList = orderService.getByEmailAndOrderNo(user.getUserEmail(), orderNo);
        // 计算商品总价
        for (Order order : orderList) {
            totalPrice = BigDecimalUtil.add(totalPrice.doubleValue(), order.getProductTotalPrice().doubleValue());
        }

        modelMap.put("totalPrice", totalPrice);
        modelMap.put("orderNo", orderNo);
        totalPrice = new BigDecimal("0.0");
        // 确认收货地址
        Integer shippingId = orderList.get(0).getShippingId();
        // 查询收货地址
        ShippingVo shipping = shippingVoService.getByShippingId(shippingId);
        modelMap.put("shipping", shipping);
        return "order_detail";

    }

    /**
     * 通过支付状态查询订单
     */
    @RequestMapping("order/getOrderStatus")
    @ResponseBody
    public ServerResponse getOrderStatus(HttpServletRequest request,@RequestParam("orderNo") Long orderNo) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(Const.ERROR_CODE, "查询失败,请先登录");
        }
        List<Order> orderList = orderService.findByUserEmailAndStatus(user.getUserEmail(), orderNo);
        if (CollectionUtils.isEmpty(orderList)) {
            return ServerResponse.createByErrorCodeMessage(Const.ERROR_CODE, "查询失败");
        }
        return ServerResponse.createBySuccess("查询成功", Const.SUCCESS_CODE);
    }

}
